package net.tarine.gastronomi.client;


public class ParamMap {
	
	private static final int MAX_PARAMS = 10;
	
	private Param[] paramArray = new Param[MAX_PARAMS];
	private int idx = 0;
	
	public void addParam(String key, String value) {
		Param p = new Param(key, value);
		paramArray[idx]=p;
		idx++;
	}
	
	/** can't return empty strings.
	 * it's only null or a string longer than 0
	 * @param key
	 * @return
	 */
	public String getValue(String key) {
		for (int i=0; i<=idx; i++) {
			Param p = paramArray[i];
			if (p != null) {
				if (key.equals(p.getKey())) {
					if (p.getValue() != null) {
						if (p.getValue().length()>0) {
							return p.getValue();
						}
					}
				}
			}
		}
		return null;
	}
	
	public Integer getIntValue(String key) {
		String value = getValue(key);
		Integer result = null;
		try {
			result = Integer.parseInt(value);
		} catch (NumberFormatException e) {	}
		return result;
	}
	
	public String getParamsStateString(String nextState) {
		String result = nextState+HistoryMgr.SEPARATOR_TOKEN;
		for (int i=0; i<MAX_PARAMS; i++) {
			Param p = paramArray[i];
			if (p != null) {
				if (p.getValue() != null) {
					if (!p.getValue().equals("")) {
						result += p.getKey() + HistoryMgr.SEPARATOR_VALUES + p.getValue() + HistoryMgr.SEPARATOR_PARAMS;
					}
				}
			}
		}
		result = result.substring(0, result.length()-1);
		return result;
	}
	
	@Override
	public String toString() {
		String result = "{";
		for (int i=0; i<=idx; i++) {
			if (paramArray[i] != null) result += paramArray[i].toString();
		}
		return result+"}";
	}
	
	// Inner class Param
	
	class Param {

		private String key;
		private String value;
				
		public Param(String key, String value) {
			this.key = key;
			this.value = value;
		}

		public String getKey() {
			return key;
		}

		public String getValue() {
			return value;
		}

		@Override
		public String toString() {
			return "["+key+"="+value+"]";
		}
		
	}
}
